package org.springboot3.project.web.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
@ConditionalOnProperty(prefix = "nacos.discovery", name = "server-addr")
@EnableConfigurationProperties(NacosProperties.class)
public class NacosConfiguration {

    @Bean
    @ConditionalOnMissingBean(ConfigService.class)
    public ConfigService nacosConfigService(final NacosProperties nacosProp) throws Exception {
        Properties properties = new Properties();

        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosProp.getServerAddr());
        if (StringUtils.isNotBlank(nacosProp.getNamespace())) {
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosProp.getNamespace());
        }
        if (StringUtils.isNotBlank(nacosProp.getUsername())) {
            properties.setProperty(PropertyKeyConst.USERNAME, nacosProp.getUsername());
        }
        if (StringUtils.isNotBlank(nacosProp.getPassword())) {
            properties.setProperty(PropertyKeyConst.PASSWORD, nacosProp.getPassword());
        }
        if (StringUtils.isNotBlank(nacosProp.getContextPath())) {
            properties.setProperty(PropertyKeyConst.CONTEXT_PATH, nacosProp.getContextPath());
        }

        return NacosFactory.createConfigService(properties);
    }
}
